package com.wangjiacai.utils.web.handler;


import com.wangjiacai.utils.enums.ResultEnum;
import com.wangjiacai.utils.web.exception.CodeMessageException;
import com.wangjiacai.utils.output.ResultVO;
import com.wangjiacai.utils.utils.ResultVOUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;


@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(CodeMessageException.class)
    @ResponseBody
    public ResultVO handlerException(CodeMessageException exception) {
        return ResultVOUtil.error(exception);
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultVO handlerException(Exception exception){
        Throwable throwable=exception;
        while (throwable.getCause()!=null){
            throwable=throwable.getCause();
        }
        if(throwable instanceof ConstraintViolationException) {
            return handlerException((ConstraintViolationException) throwable);
        }
        exception.printStackTrace();
        return ResultVOUtil.error(ResultEnum.SERVER_ERROR);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResultVO handlerException(ConstraintViolationException exception) {
        Set<ConstraintViolation<?>> set=exception.getConstraintViolations();
        for(ConstraintViolation constraintViolation:set){
            return ResultVOUtil.error(ResultEnum.SERVER_ERROR.getCode(),constraintViolation.getMessage());
        }
        return ResultVOUtil.error(ResultEnum.SERVER_ERROR);
    }
}
